<?php


namespace app\seller\controller;

use think\Db;
use app\admin\model\UserCategoryRmb;
use addons\epay\library\Service;
use Yansongda\Pay\Pay;


class Order extends Base
{
    public function index()
    {
        $day = input('day');
        $length = input('length');
        $fangjianid = $this->fangjianIds();
        $query = Db::name('order')
            ->field('ims_ymq_changdi_fangjian.name as fj_name,ims_ymq_changdi_order.refund_money,
            ims_ymq_changdi_user.nickname,ims_ymq_changdi_order.pay_type,ims_ymq_changdi_order.quan_price,ims_ymq_changdi_order.real_price,ims_ymq_changdi_order.id,
            ims_ymq_changdi_order.x_status,ims_ymq_changdi_order.price,ims_ymq_changdi_order.createtime,ims_ymq_changdi_order.status,ims_ymq_changdi_order.x_status,
            ims_ymq_changdi_order.is_write_off,ims_ymq_changdi_order.fuwu,ims_ymq_changdi_order.fuwu_sc,ims_ymq_changdi_order.number')
            ->where("fangjian_id", "in", $fangjianid)
            ->join("ims_ymq_changdi_fangjian", "ims_ymq_changdi_fangjian.id = ims_ymq_changdi_order.fangjian_id", "left")
            ->join("ims_ymq_changdi_user", "ims_ymq_changdi_user.id = ims_ymq_changdi_order.user_id", "left");
        if ($day == 'today') {
            $query = $query->whereTime('ims_ymq_changdi_order.createtime', 'today');
        } elseif ($day == 'day7') {
            $query = $query->whereTime('ims_ymq_changdi_order.createtime', 'between', [date('Y-m-d 00:00:00', strtotime("-7 day")), date('Y-m-d 23:59:59')]);
        } elseif ($day == 'month') {
            $query = $query->whereTime('ims_ymq_changdi_order.createtime', 'month');
        }
        $list = $query->limit($length, 20)->order("ims_ymq_changdi_order.id desc")->select();
        $state = [0 => '未支付', 1 => '待消费', 2 => '消费中', 3 => '已完成', 4 => '已取消', 5 => '续费'];
        $x_state = [0 => '正常订单', 1 => '续费订单', 2 => '商家代下单'];
        $is_write_off = [0 => '未核销', 1 => '已核销'];
        $pay_type = [1 => '微信', 2 => '余额', 0 => '未知'];
        foreach ($list as &$v) {
            $v['createtime'] = date('Y-m-d H:i:s', $v['createtime']);
            $v['time'] = strtotime($v['fuwu']);
            $shichuang = $v['time'] + $v['fuwu_sc'] * 60 * 60;
            $v['j_time'] = date('Y/m/d H:i:s', $shichuang);
            $v['_status'] = $state[$v['status']];
            $v['_is_write_off'] = $is_write_off[$v['is_write_off']];
            $v['_x_status'] = $x_state[$v['x_status']];
            $v['_pay_type'] = $pay_type[$v['pay_type']];
        }
        return $this->success('获取成功', $list);
    }

    public function detail()
    {
        $id = input('id');
        $fangjianid = $this->fangjianIds();
        $query = Db::name('order')
            ->field('ims_ymq_changdi_fangjian.name as fj_name,ims_ymq_changdi_order.refund_money,
            ims_ymq_changdi_user.nickname,ims_ymq_changdi_order.pay_type,ims_ymq_changdi_order.quan_price,ims_ymq_changdi_order.real_price,ims_ymq_changdi_order.id,
            ims_ymq_changdi_order.x_status,ims_ymq_changdi_order.price,ims_ymq_changdi_order.createtime,ims_ymq_changdi_order.status,ims_ymq_changdi_order.x_status,
            ims_ymq_changdi_order.is_write_off,ims_ymq_changdi_order.fuwu,ims_ymq_changdi_order.fuwu_sc,ims_ymq_changdi_order.number')
            ->where("fangjian_id", "in", $fangjianid)
            ->where("ims_ymq_changdi_order.id", "=", $id)
            ->join("ims_ymq_changdi_fangjian", "ims_ymq_changdi_fangjian.id = ims_ymq_changdi_order.fangjian_id", "left")
            ->join("ims_ymq_changdi_user", "ims_ymq_changdi_user.id = ims_ymq_changdi_order.user_id", "left");
        $detail = $query->find();
        $state = [0 => '未支付', 1 => '待消费', 2 => '消费中', 3 => '已完成', 4 => '已取消', 5 => '续费'];
        $x_state = [0 => '正常订单', 1 => '续费订单', 2 => '商家代下单'];
        $is_write_off = [0 => '未核销', 1 => '已核销'];
        $pay_type = [1 => '微信', 2 => '余额', 0 => '未知'];
        $detail['createtime'] = date('Y-m-d H:i:s', $detail['createtime']);
        $detail['time'] = strtotime($detail['fuwu']);
        $shichuang = $detail['time'] + $detail['fuwu_sc'] * 60 * 60;
        $detail['j_time'] = date('Y/m/d H:i:s', $shichuang);
        $detail['_status'] = $state[$detail['status']];
        $detail['_is_write_off'] = $is_write_off[$detail['is_write_off']];
        $detail['_x_status'] = $x_state[$detail['x_status']];
        $detail['_pay_type'] = $pay_type[$detail['pay_type']];
        return $this->success('获取成功', $detail);
    }

    public function refund()
    {
        $id = input('id');
        $refund_money = floatval(input('money'));
        $fangjianid = $this->fangjianIds();
        $detail = Db::name('order')
            ->where("fangjian_id", "in", $fangjianid)
            ->where("id", "=", $id)
            ->find();
        if ($detail['status'] != 2) {
            return $this->error('消费中订单才可以退款');
        }
        if (!$refund_money) {
            return $this->error('请输入退款金额');
        }
        if ($refund_money > ($detail['real_price'] - $detail['refund_money'])) {
            return $this->error('最大退款金额' . ($detail['real_price'] - $detail['refund_money']) . "元");
        }
        $category_id = Db::name('fangjian')->where("id", "in", $detail['fangjian_id'])->value('category_id');
        if ($detail['pay_type'] == 1) {
            $config2 = Service::getConfig('wechat');
            $config = [
                'appid' => '',
                'app_id' => '',
                'miniapp_id' => $config2['miniapp_id'], // 小程序 APPID
                'mch_id' => $config2['mch_id'],
                'key' => $config2['key'],
                'notify_url' => $config2['notify_url'],
                'cert_client' => ROOT_PATH . 'addons/epay/certs/apiclient_cert.pem', // optional，退款等情况时用到
                'cert_key' => ROOT_PATH . 'addons/epay/certs/apiclient_key.pem',// optional，退款等情况时用到
                'log' => [ // optional
                    'file' => ROOT_PATH . 'runtime/log/epaylogs/wechat-2022-08-31.log',
                    'level' => 'info', // 建议生产环境等级调整为 info，开发环境为 debug
                    'type' => 'single', // optional, 可选 daily.
                    'max_file' => 30, // optional, 当 type 为 daily 时有效，默认 30 天
                ],
                'http' => [ // optional
                    'timeout' => 10,
                    'connect_timeout' => 10,
                ],
                'mode' => 'normal', // optional, dev/hk;当为 `hk` 时，为中国香港 gateway。
            ];
            $orders = [
                'transaction_id' => $detail['transaction_id'],
                'out_refund_no' => time(),
                'total_fee' => $detail['price'] * 100,
                'refund_fee' => $refund_money * 100,
                'refund_desc' => "商家主动退款,订单:{$detail['number']}",
                'type' => 'miniapp',
            ];
            $pay = Pay::wechat($config)->refund($orders);
        } else if ($detail['pay_type'] == 2) {
            UserCategoryRmb::change(
                $detail['user_id'],
                $category_id,
                $refund_money,
                "商家主动退款,订单ID:{$id},加回余额{$refund_money}元"
            );
        }
        $fuwu_sc = (time() - strtotime($detail['fuwu'])) / 3600;

        Db::name('order')->where("id", "=", $id)->update([
            'refund_money' => $refund_money + $detail['refund_money'],
            'settlement_money' => $detail['settlement_money'] - $refund_money,
            'fuwu_sc' => round($fuwu_sc, 2),
        ]);
        return $this->success("退款成功");
    }
}
